package kmi.droid.livewallpaper.gl;

import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;

public class EGLFactory
{
	interface EGLContextFactory
	{
		EGLContext createContext(EGL10 egl, EGLDisplay display,
				EGLConfig eglConfig);

		void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context);
	}

	interface EGLWindowSurfaceFactory
	{
		EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display,
				EGLConfig config, Object nativeWindow);

		void destroySurface(EGL10 egl, EGLDisplay display, EGLSurface surface);
	}

	/**
	 * An interface for customizing the eglCreateContext and eglDestroyContext
	 * calls.
	 * 
	 * 
	 * This interface must be implemented by clients wishing to call
	 * {@link GLWallpaperService#setEGLContextFactory(EGLContextFactory)}
	 */

	public static class DefaultContextFactory implements EGLContextFactory
	{
		public EGLContext createContext(EGL10 egl, EGLDisplay display,
				EGLConfig config)
		{
			return egl.eglCreateContext(display, config, EGL10.EGL_NO_CONTEXT,
					null);
		}

		public void destroyContext(EGL10 egl, EGLDisplay display,
				EGLContext context)
		{
			egl.eglDestroyContext(display, context);
		}
	}

	public static class DefaultWindowSurfaceFactory implements
			EGLWindowSurfaceFactory
	{
		public EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display,
				EGLConfig config, Object nativeWindow)
		{
			// this is a bit of a hack to work around Droid init problems - if
			// you
			// don't have this, it'll get hung up on orientation changes
			EGLSurface eglSurface = null;

			while (eglSurface == null)
			{
				try
				{
					eglSurface = egl.eglCreateWindowSurface(display, config,
							nativeWindow, null);
				} catch (Throwable t)
				{
				} finally
				{
					if (eglSurface == null)
					{
						try
						{
							Thread.sleep(10);
						} catch (InterruptedException t)
						{
						}
					}
				}
			}
			return eglSurface;
		}

		public void destroySurface(EGL10 egl, EGLDisplay display,
				EGLSurface surface)
		{
			egl.eglDestroySurface(display, surface);
		}
	}
}